<template>
  <div class="bg_white" style="height: calc(100vh - 198px);">
    <div style="margin: 0 0 10px 0">
      <a-button type="primary" icon="usergroup-add" @click="addRole()" v-if="isAdmin">
        添加角色
      </a-button>
      <!-- <a-button style="margin-left: 8px">批量导入</a-button>
      <a-button style="margin-left: 8px">调整排序</a-button>
      <a-button style="margin-left: 8px">批量删除</a-button> -->
    </div>

    <div style="padding: 10px 0; background: #fff; border-radius: 6px">
      <!-- :scroll="{ x: 'calc(700px + 50%)', y: 720 }" -->
      
      <!-- 注释勾表格勾选框  -->
      <!-- :row-selection="rowSelection" -->
      <a-table
        :columns="columns"
        :data-source="data"
        bordered
        :rowKey="
          (record, index) => {
            return index;
          }
        "
      >
        <span slot="status" slot-scope="text, record">
          {{ record.status == 1 ? "启用" : "禁用" }}
        </span>
        <span slot="action" slot-scope="text, record" v-if="isAdmin">
          <a @click="actionUser(record.id)" style="color: #ff4d4f;">绑定用户</a>
          <a-divider type="vertical" />
          <a @click="removeUser(record.id)" style="color: #ff4d4f;">移除用户</a>
          <a-divider type="vertical" />
          <a @click="showDrawer(record.id)" style="color: #ff4d4f;">绑定菜单</a>
          <a-divider type="vertical" />
          <a @click="UpdateRole(record)" style="color: #ff4d4f;">修改角色</a>
          <a-divider type="vertical" />
          <a @click="deleteRole(record.id)" style="color: #ff4d4f;">删除角色</a>
        </span>
      </a-table>
      <a-drawer
        :title="title"
        placement="right"
        :closable="false"
        :visible="visible"
        :after-visible-change="afterVisibleChange"
        @close="onClose"
        width="600px"
      >
        <el-tree
          v-model="checkedKeys"
          checkable
          show-checkbox
          node-key="id"
          ref="trees"
          :props="replaceFields"
          :data="treeData"
          :default-checked-keys="checkedKeys"
          @check="onCheck"
        
        />
        <div style="margin-top: 20px; margin-top: 20px">
          <a-button style="margin-left: 20px" @click="onClose()"
            >取 消</a-button
          >
          <a-button
            type="primary"
            style="margin-left: 20px"
            @click="submitPermisson()"
            >确 定</a-button
          >
        </div>
      </a-drawer>
      <a-modal
        :title="title"
        :visible="addRoleVisible"
        :confirm-loading="confirmLoading"
        @ok="submitForm('roleValidateForm')"
        @cancel="resetForm('roleValidateForm')"
      >
        <el-form
          :model="roleValidateForm"
          ref="roleValidateForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="角色名"
            prop="roleName"
            :rules="[{ required: true, message: '角色名不能为空' }]"
          >
            <el-input
              v-model="roleValidateForm.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否为动态" prop="category">
            <el-input v-model="roleValidateForm.category"></el-input>
          </el-form-item>
          <el-form-item label="角色状态">
            <el-select
              v-model="roleValidateForm.status"
              default-first-option="0"
              style="width: 100%;"
            >
              <el-option label="禁用" value="0"></el-option>
              <el-option label="启用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入内容"
              v-model="roleValidateForm.description"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </a-modal>

      <a-drawer
        width="620px"
        :title="title"
        placement="right"
        :closable="false"
        :visible="userVisible"
        :after-visible-change="afterVisibleChange"
        @close="onUserClose"
      >
        <div style="margin-left: 10px">
          <el-input
            v-model="userName"
            placeholder="请输入用户名"
            style="width: 250px"
            size="medium"
          /><el-button size="medium" style="margin-left: 10px" type="primary" @click="seach">
            <i class="el-icon-search"></i
            ><span style="margin-left: 10px">搜索</span></el-button
          >
        </div>
        <div style="margin: 10px;">
        <el-table
          ref="multipleTable"
          :data="userData"
          tooltip-effect="dark"
          @selection-change="onUserSelectChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="displayName"
            label="用户名称"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="department"
            label="部门名称"
          ></el-table-column>
        </el-table>
        </div>

        <a-pagination
          style="margin: 10px"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @showSizeChange="onShowSizeChange"
          @change="pageChange"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
          </template>
        </a-pagination>
        <div>
          <a-button style="margin:10px" @click="onUserClose()"
            >取 消</a-button
          >
          <a-button
            style="margin-left: 10px"
            type="primary"
            @click="submitUser()"
            >确 定</a-button
          >
        </div>
      </a-drawer>
    </div>
  </div>
</template>

<script>
import contacts from "@/api/organizations";
const columns = [
  {
    title: "用户组名称",
    dataIndex: "roleName",
  },
  {
    title: "描述",
    dataIndex: "description",
  },
  {
    title: "状态",
    scopedSlots: { customRender: "status" },
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
  },
];

const data = [];
for (let i = 0; i < 46; i++) {
  data.push({
    key: i,
    name: `Edward King ${i}`,
    age: 32,
    address: `London, Park Lane no. ${i}`,
  });
}

const x = 3;
const y = 2;
const z = 1;
const gData = [];

const generateData = (_level, _preKey, _tns) => {
  const preKey = _preKey || "0";
  const tns = _tns || gData;

  const children = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({ title: key, key, scopedSlots: { title: "title" } });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

const dataList = [];
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({ key, title: key });
    if (node.children) {
      generateList(node.children);
    }
  }
};
generateList(gData);

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
export default {
  data() {
    return {
      addOrdel:0,
      roleValidateForm: {
        roleId: "",
        roleName: "",
        category: "",
        status: "1",
        description: "",
      },
      isAdmin:false,
      userName: "",
      addOrUpdate: 0,
      selectionKeys: [],
      tableData: [],
      visible: false,
      addRoleVisible: false,
      expandedKeys: [],
      searchValue: "",
      autoExpandParent: true,
      gData,
      userVisible: false,
      treeData: [],
      pageSize: 10,
      current: 1,
      userData: [],
      title: "",
      replaceFields: {
        label: "menuName",
        key: "id",
        children: "children",
      },
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      roleId: "",
      data,
      total: 0,
      columns,
      selectedRowKeys: [], // Check here to configure the default column
      selectedUserKeys: [],
      selParentList: [],
    };
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this;
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection,
      };
    },
  },
  mounted() {
    this.getRoleByUser();
    this.getRole();
  },
  watch: {
    checkedKeys(val) {},
  },
  methods: {
    removeUser(val){
      this.addOrdel=1
      this.roleId = val;
      this.title = "移除用户";
      this.userVisible = true;
      this.getUserByRoleIds(val)
    },
    getUserByRoleIds(id){
      let data={
        page: this.current,
        size: this.pageSize,
        roleId:id
      }
      contacts.getUserByRoles(data).then((res)=>{
        this.userData = res.data.user
        this.total = res.data.total;
      })
    },
    seach() {
      this.getUserInfo();
    },
    deleteRole(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          contacts.delRole(id).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getRole();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    UpdateRole(val) {
      this.addOrUpdate = 1;
      (this.roleValidateForm.roleName = val.roleName),
        (this.roleValidateForm.category = val.category),
        (this.roleValidateForm.status = val.status),
        (this.roleValidateForm.description = val.description),
        (this.roleValidateForm.roleId = val.id);
      this.addRoleVisible = true;
    },
    statusChange(val) {
      this.form.status = val;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let msg = "";
          if (this.addOrUpdate == 0) {
            msg = "角色增加成功";
          } else {
            msg = "角色修改成功";
          }
          contacts.addRole(this.roleValidateForm).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(msg);
              this.resetForm(formName);
              this.addRoleVisible = false;
              this.getRole();
            }
          });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.addRoleVisible = false;
      this.$refs[formName].resetFields();
    },
    handleChange(e) {
      this.checkNick = e.target.checked;
      this.$nextTick(() => {
        this.form.validateFields(["roleName"], { force: true });
      });
    },
    addRole() {
      (this.addOrUpdate = 0), (this.title = "增加角色");
      this.addRoleVisible = true;
    },
    handleCancel() {
      this.addRoleVisible = false;
    },
    bindRoleAndMenu() {
     
    
      let data = {
        menuIds: this.checkedKeys.concat(this.selParentList),
        roleId: this.roleId,
      };
      contacts.bindMenu(data).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("绑定成功");
          this.onClose();
        }
      });
    },
    submitUser() {
      this.selectedUserKeys = this.selectedUserKeys.map((item) => {
        return item.id;
      });
      let data = {
        userIds: this.selectedUserKeys,
        roleId: this.roleId,
      };
      if(this.addOrdel ==0){
        contacts.bindUser(data).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("绑定成功");
          this.onUserClose();
        }
      });
      }else{
        contacts.removeUserByRole(data).then((res)=>{
          if (res.data.code == 200) {
          this.$message.success("移除成功");
          this.onUserClose();
        }else{
          this.$message.success("系统错误，请联系管理员");
          this.onUserClose();
        } 
        })
      }
    },
    onUserSelectChange(selectedUserKeys, val) {
      this.selectedUserKeys = selectedUserKeys;
    },
    pageChange(val) {
      this.current = val;
      this.getUserInfo();
    },
    submitPermisson() {
    
      this.bindRoleAndMenu();
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.getUserInfo();
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys, e) {
      console.log("=======",e)
      this.checkedKeys = e.checkedKeys;
      this.selParentList = e.halfCheckedKeys;
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys;
    },
    showDrawer(id) {
      this.getAllMenuInfo(id);

      this.title = "绑定权限";
      this.roleId = id;
      this.visible = true;
      this.getMenuById(id);
    },
    onUserClose() {
      this.current=1
      this.pageSize=10
      this.userVisible = false;
    },
    onClose() {
      this.checkedKeys = [];
      this.visible = false;
    },
    async getMenuById(id) {
      contacts.getMenuByRole(id).then((res) => {
        this.$nextTick(() => {
          for (let i = 0; i < res.data.length; i++) {
          this.checkedKeys.push(res.data[i].id);
        }
        this.$refs.trees.setCheckedKeys(this.checkedKeys)
        })
       
      });

      // this.defaultChecked()
     
    },

    
    defaultChecked () { // 默认选中
      this.$nextTick(() => {
        // const arr = []
        // this.menus.forEach(item => {
        //   if (!this.$refs.tree.getNode(item.id).childNodes || !this.$refs.tree.getNode(item.id).childNodes.length) {
        //     arr.push(item.id)
        //   }
        // })
       
       
      })
    },
   async getAllMenuInfo(id) {
     await contacts.getMenu().then((res) => {
        this.treeData = res.data;
     
      });
     
      
    },
    actionUser(id) {
      this.addOrdel=0
      this.roleId = id;
      this.title = "绑定用户";
      this.userVisible = true;
      this.getUserInfo();
    },
    async getUserInfo() {
      let data = {
        userName: this.userName,
        page: this.current,
        size: this.pageSize,
      };
      contacts.getUser(data).then((res) => {
        this.userData = res.data.user;
        this.total = res.data.total;
        this.getUserByRoleId();
      });
    },
    getUserByRoleId() {
      contacts.getUserByRole(this.roleId).then((res) => {
        const backList = res.data.user;

        backList.forEach((item) => {
          //回显
          this.userData.forEach((row) => {
            if (row.id == item.id) {
              this.$refs.multipleTable.toggleRowSelection(row, true);
            }
          });
        });
      });
    },
    getRoleByUser() {
      contacts.getRoleByUser().then((res) => {
        for (let i = 0; i < res.data.data.deptCodeRole.length; i++) {
          if (res.data.data.deptCodeRole[i].code == "t001") {
            this.isAdmin = true;
          }
        }
      });
    },
    actionMenu(id) {
      this.$message.success(id);
    },
    getRole() {
      contacts.getRole().then(
        (res) => {
          this.data = res.data;
        },
        (err) => {}
      );
    },

    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChange(e) {
      const value = e.target.value;
      const expandedKeys = dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, gData);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.ant-layout-header {
  background: #03212100 !important;
}

.vtl {
  .vtl-drag-disabled {
    background-color: #d0cfcf;

    &:hover {
      background-color: #d0cfcf;
    }
  }

  .vtl-disabled {
    background-color: #d0cfcf;
  }
}
</style>
